//
//  MagageQRCodeViewController.m
//  FreshMember
//
//  Created by qyc on 2019/7/3.
//  Copyright © 2019 qyc. All rights reserved.
//

#import "HAQrCodeViewController.h"
#import "HAInPutCodeViewController.h"

#import "SGQRCode.h"
#import "CommentTool.h"
#import "HAOrderModel.h"

@interface HAQrCodeViewController () {
    SGQRCodeObtain *obtain;
}

@property (nonatomic, strong) SGQRCodeScanView *scanView;
@property (nonatomic, strong) UILabel *promptLabel;
@property (nonatomic, strong) UIButton *inputBtn;
@property (nonatomic, assign) BOOL stop;

@end

@implementation HAQrCodeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (_stop) {
        [obtain startRunningWithBefore:nil completion:nil];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.scanView addTimer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.scanView removeTimer];
}

- (void)dealloc {
    NSLog(@"WBQRCodeVC - dealloc");
    [self removeScanningView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor blackColor];
    obtain = [SGQRCodeObtain QRCodeObtain];
    
    [self setupQRCodeScan];
    [self setupNavigationBar];
    [self.view addSubview:self.scanView];
    [self.view addSubview:self.promptLabel];
    [self.view addSubview:self.inputBtn];
}

- (void)setupQRCodeScan {
    __weak typeof(self) weakSelf = self;
    
    SGQRCodeObtainConfigure *configure = [SGQRCodeObtainConfigure QRCodeObtainConfigure];
    configure.openLog = YES;
    configure.rectOfInterest = CGRectMake(0.05, 0.2, 0.7, 0.6);
    // 这里只是提供了几种作为参考（共：13）；需什么类型添加什么类型即可
    NSArray *arr = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    configure.metadataObjectTypes = arr;
    
    [obtain establishQRCodeObtainScanWithController:self configure:configure];
    [obtain startRunningWithBefore:^{
        [[MBProgressHUDTool shareProgressHUD] showHUDAddedTo:self.view];
    } completion:^{
        [[MBProgressHUDTool shareProgressHUD] hideHUD];
    }];
    [obtain setBlockWithQRCodeObtainScanResult:^(SGQRCodeObtain *obtain, NSString *result) {
        if (result) {
            
            [obtain stopRunning];
            weakSelf.stop = YES;
            
            NSString *order_id = result;
            
            [[MBProgressHUDTool shareProgressHUD] showHUDAddedTo:weakSelf.view];
            // 请求当前订单状态
            [[HAUserAppApi sharedApi] requestRiderOrderStatusWithOrder_id:order_id completionHandler:^(id  _Nonnull successHandler) {
                // 旧的订单状态
                UserOrderProductStatusType type = [successHandler[@"order_status"] integerValue];
                // 新的订单状态
                UserOrderProductStatusType upType;
                if (type == UserOrdersProductTypeWithUserAlreadyPay) { // 已支付
                    upType = UserOrdersProductTypeWithHorsemanReceiving;
                } else if (type == UserOrdersProductTypeWithExchangeSuccess || type == UserOrdersProductTypeWithReturnApplyMoneySuccess) { // 换货通过审核
                    upType = UserOrdersProductTypeWithExpressageDelivery;
                } else {
                    [[MBProgressHUDTool shareProgressHUD] hideHUD];
                    [CustomProgressHUD showMessage:@"该订单无法接单" time:0];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                    return ;
                }
                
                // 接单
                [[HAUserAppApi sharedApi] requestRiderScanOrderStatusWithOrder_status:upType order_id:order_id rider_uid:[[ReadWriteUserInfoTool sharedUserInfo] getUserId] completionHandler:^(id  _Nonnull successHandler) {
                
                    [[MBProgressHUDTool shareProgressHUD] hideHUD];
                    [CustomProgressHUD showMessage:@"接单成功" time:0];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                    
                } errorHandler:^(id  _Nonnull errorHandler) {
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }];
                
            } errorHandler:^(id  _Nonnull errorHandler) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }];
        }
    }];
}

- (void)setupNavigationBar {
    [self configNavigationTitle:@"扫一扫"];
}

- (SGQRCodeScanView *)scanView {
    if (!_scanView) {
        _scanView = [[SGQRCodeScanView alloc] initWithFrame:CGRectMake(0, k_Height_NavBar, kWindowW, kWindowH - k_Height_NavBar)];
        // 静态库加载 bundle 里面的资源使用 SGQRCode.bundle/QRCodeScanLineGrid
        // 动态库加载直接使用 QRCodeScanLineGrid
        _scanView.scanImageName = @"SGQRCode.bundle/QRCodeScanLineGrid";
        _scanView.scanAnimationStyle = ScanAnimationStyleGrid;
        _scanView.cornerLocation = CornerLoactionOutside;
        _scanView.cornerColor = [UIColor orangeColor];
    }
    return _scanView;
}

- (void)removeScanningView {
    [self.scanView removeTimer];
    [self.scanView removeFromSuperview];
    self.scanView = nil;
}

- (UILabel *)promptLabel {
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc] init];
        _promptLabel.backgroundColor = [UIColor clearColor];
        CGFloat promptLabelX = 0;
        CGFloat promptLabelY = 0.3 * (kWindowH - k_Height_NavBar) + 0.7 * kWindowW;
        CGFloat promptLabelW = kWindowW;
        CGFloat promptLabelH = 25;
        _promptLabel.frame = CGRectMake(promptLabelX, promptLabelY, promptLabelW, promptLabelH);
        _promptLabel.textAlignment = NSTextAlignmentCenter;
        _promptLabel.font = [UIFont boldSystemFontOfSize:13.0];
        _promptLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6];
        _promptLabel.text = @"将二维码/条码放入框内，即可自动扫描";
    }
    return _promptLabel;
}

- (UIButton *)inputBtn {
    if (!_inputBtn) {
        _inputBtn = [[UIButton alloc] init];
        _inputBtn.backgroundColor = UIColorFromRGB(0x4E8CEE);
        CGFloat promptLabelX = 40;
        CGFloat promptLabelY = 0.8 * kWindowH;
        CGFloat promptLabelW = kWindowW - 80;
        CGFloat promptLabelH = 44;
        _inputBtn.frame = CGRectMake(promptLabelX, promptLabelY, promptLabelW, promptLabelH);
        [_inputBtn setTitle:@"手动输入订单号" forState:UIControlStateNormal];
        [_inputBtn addTarget:self action:@selector(inputClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _inputBtn;
}

// 去手动输入页面
- (void)inputClick {
    HAInPutCodeViewController *vc = [[HAInPutCodeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
